`

N O T E

Remember that running port scanners in aggressive modes increases the

chances of getting caught, especially if the target implements an Intru-

sion Detection System (IDS) or Endpoint Detection and Response

(EDR) system. Also, if you scan at a rapid pace, some devices could

crash as a result of the network flood.

Exercise 4: Organizing Scan Results by Port Number

Its often useful to sort your scan results into categories of

interest. For example, you could dump results for each IP address in

a dedicated file or organize the results based on the versions of

software found. In this exercise, we’ll organize our scan results

based on port numbers. Lets write a script that does the following:

1. Runs Nmap against hosts in a file.

2. Uses bash to create individual files whose filenames are open

ports.

3. In each file, writes the IP address on which the corresponding

port was open.

At the end of this exercise, well have a bunch of files, such as

port-22.txt, port-80.txt, and port-8080.txt, and in each file, we’ll see

one or more IP addresses at which that port was found to be open.

This can be useful when you have a large number of target hosts and

want to attack them in clusters by targeting specific protocols

associated with given ports. Listing 4-11 shows the script’s code.

#!/bin/bash

HOSTS_FILE="172-16-10-hosts.txt"

1 NMAP_RESULT=$(nmap -iL ${HOSTS_FILE} --open | grep "Nmap scan report\|tcp open")

# read the nmap output line by line

while read -r line; do

2 if echo "${line}" | grep -q "report for"; then

ip=$(echo "${line}" | awk -F'for ' '{print $2}')

else

3 port=$(echo "${line}" | grep open | awk -F'/' '{print $1}')

4 file="port-${port}.txt"

5 echo "${ip}" >> "${file}"

fi

done <<< "${NMAP_RESULT}"

Listing 4-11

Organizing scan results by port using bash

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks